using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using Microsoft.TeamFoundation.WebAccess.UI;
using Microsoft.TeamFoundation.WebAccess.Controls;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;

namespace Stratman.Web.VSTS.UI.Pages.Timesheet
{
    /// <summary>
    /// Page that allows the user to add a work item to a week so that they may allocate hours to it.
    /// </summary>
    public partial class Add : WebAccessPage
    {
        /// <summary>
        /// The display name of the current user
        /// </summary>
        protected string openUserDisplayName = "";
        /// <summary>
        /// The beginning of the week to which we are adding this work item
        /// </summary>
        DateTime startOfWeek;

        /// <summary>
        /// Initializes the various members of the class.
        /// </summary>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ActiveTab = "Timesheet";
        }

        /// <summary>
        /// Event handler that is invoked when the page is loading; initializes the various member variables and
        /// also saves placeholders for the new work item links to the timesheets so that allocation boxes will
        /// appear the next time the user accesses that week.
        /// </summary>
        protected void Page_Load()
        {
            // Create a connection to the database
            SqlConnection databaseConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDatabase"].ConnectionString);
            SqlCommand command = null;
            SqlDataReader reader = null;

            databaseConnection.Open();

            command = new SqlCommand("usp_RS_UserInfo", databaseConnection);

            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@sid", Request.LogonUserIdentity.User.ToString()));

            reader = command.ExecuteReader();
            reader.Read();

            openUserDisplayName = (string)reader["displayName"];
            reader.Close();

            startOfWeek = DateTime.ParseExact(Request.QueryString["ws"], "yyyy-MM-dd", null);
            startOfWeek = startOfWeek.AddDays(-1 * (int)startOfWeek.DayOfWeek);

            if (!String.IsNullOrEmpty(Request.Form["selectedWorkItems"]))
            {
                // Get the IDs of the work items that the user selected
                string[] workItemIds = Request.Form["selectedWorkItems"].Split(',');
                string fieldName = "";
                TimesheetSettings settings = (TimesheetSettings)ConfigurationManager.GetSection("timesheetSettings");

                foreach (TimeAmount amount in settings.TimeAmounts)
                {
                    if (Request.Form["timeAmountType"].ToLower() == amount.Label.ToLower())
                    {
                        fieldName = amount.CompletedHoursFieldName;
                        break;
                    }
                }
                
                foreach (string workItemId in workItemIds)
                {
                    // Add an entry to the TimesheetEntries table with a hours value of 0 so that this work item 
                    // will show up for the week, but will have no hours associated with it
                    command = new SqlCommand("usp_INS_WorkItemForWeek", databaseConnection);
                    string sid = Request.LogonUserIdentity.User.ToString();

                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@sid", Request.LogonUserIdentity.User.ToString()));
                    command.Parameters.Add(new SqlParameter("@startOfWeek", startOfWeek));
                    command.Parameters.Add(new SqlParameter("@workItemId", Convert.ToInt32(workItemId)));
                    command.Parameters.Add(new SqlParameter("@fieldName", fieldName));
                    
                    command.ExecuteNonQuery();
                }

                // Redirect the user to their timesheet for the week
                databaseConnection.Close();
                Response.Redirect("Explorer.aspx?ws=" + Request.QueryString["ws"]);
            }

            if (!IsPostBack)
            {
                TimesheetSettings settings = (TimesheetSettings)ConfigurationManager.GetSection("timesheetSettings");

                foreach (TimeAmount amount in settings.TimeAmounts)
                    timeAmountTypeDropdown.Items.Add(new ListItem(amount.Label, amount.CompletedHoursFieldName));
            }

            databaseConnection.Close();
        }

        /// <summary>
        /// Create a list of breadcrumb hyperlinks that will be displayed above the toolbar.
        /// </summary>
        /// <returns>
        /// A list of hyperlinks pointing to home (Index.aspx) and the timesheet for the current week.
        /// </returns>

        protected override IEnumerable<BreadCrumbSegment> CreatePageBreadCrumb()
        {
            return new BreadCrumbSegment[] { CreateBreadcrumbSegment("Home","Index.aspx"), CreateBreadcrumbSegment("Timesheet for " + openUserDisplayName, "Explorer.aspx?ws=" + Request.QueryString["ws"])};
        }

        private BreadCrumbSegment CreateBreadcrumbSegment(string name, string url)
        {
            return string.IsNullOrEmpty(url) ? new BreadCrumbSegment(name) :
            new BreadCrumbSegment(name, this.Locator.CreateLinkUrl(base.ResolveUrl(url), string.Empty, new object[0]));
        }

 

        /// <summary>
        /// Create the buttons to display in the toolbar.
        /// </summary>
        /// <returns>
        /// A list of buttons including back (goes back to the timesheet for the week) and add (adds placeholder
        /// entries for the work items specified).
        /// </returns>
        protected override StaticMenu CreatePageToolbar()
        {
 	        StaticMenu toolbar = ToolbarFactory.CreateToolbar(this, this, new ToolbarItems[] {ToolbarItems.AddToWorkitem, ToolbarItems.Separator, ToolbarItems.Home});

            toolbar.Items[0].Text = "Add Work Items";
            toolbar.Items[0].Id = "addtots";
            toolbar.Items[0].Action = "PerformAdd();";
            toolbar.Items[toolbar.Items.Count - 1].Action = "parent.location='Explorer.aspx?ws=" + startOfWeek.ToString("yyyy-MM-dd") + "'";
            toolbar.Items[toolbar.Items.Count - 1].Text = "Cancel";
            toolbar.Items[toolbar.Items.Count - 1].ImageUrl = ResolveUrl("~/Resources/Images/cancel.gif");

            return toolbar;
        }

        /// <summary>
        /// Perform any necessary rendering actions for the page, including creating the toolbar.
        /// </summary>
        protected override void RenderPage()
        {
            ContentTitle = "Add Work Items To Timesheet";
        }
    }
}
